using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Diagnostics;

namespace WorkServiceDemo.Terminal;

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;

    public Worker(ILogger<Worker> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
        var ramCounter = new PerformanceCounter("Memory", "Available MBytes");

        while (!stoppingToken.IsCancellationRequested)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            }

            var cpuUsage = cpuCounter.NextValue();
            var ramUsage = ramCounter.NextValue();

            _logger.LogInformation("CPU Usage: {0}%", cpuUsage);
            _logger.LogInformation("Available RAM: {0} MB", ramUsage);

            await Task.Delay(5000, stoppingToken);
        }
    }
}
